import json
from WebFrame.wsgi import app, redirect
from WebFrame.utils import hash, getRandom
from setting import STATICFILES_DIRS,PAY_API
from WebFrame.ORM import select, insert, Dict2Obj, update, delete
import time

USER = ['id', 'username', 'password', 'truename', 'birthday',
        'phone', 'address', 'zipcode', 'balance', 'create_time']
# BANK = ['id', 'account_num', 'create_time']
GOODS = ['id', 'name', 'tags', 'price', 'own_user', 'buy_user',
         'description', 'img', 'flags', 'create_time', 'buy_time']


def save_as(path: str, file: bytes):  # 文件保存

    with open(path, "wb") as fp:
        fp.write(file)
        fp.close()


def deal_tags(goods):
    n_g = []
    for i in goods:
        na = i
        na['tags'] = i.tags.split(' ')
        n_g.append(Dict2Obj(na))
    return n_g


def deal_goods_page(sql: str,arg, page=0, pagesize=6):
    sql_count = sql.replace('*', 'COUNT(*)')
    count = select(sql_count,arg, ['count'])[0].count
    arg=arg+(page*pagesize,(page+1)*pagesize)
    sql_page = sql+" LIMIT %s, %s"
    page_goods = select(sql_page,arg, GOODS)
    page_goods = deal_tags(page_goods)
    count_page = int(count/pagesize)+1
    return {'count': count, 'goods': page_goods, 'now_page': page+1, 'count_page': count_page, 'all_page': [i+1 for i in range(count_page)]}


@app.route('/')
def index(request):
    if request.get('REQUEST_METHOD') == 'GET':
        data = app.args
        page = data.get('page', None)

        if not page:
            page = 1
        else:
            page = int(page)
    page = page-1
    sql = 'SELECT * FROM `goods` where flags=0'
    page_goods = deal_goods_page(sql,(), page)

    return app.render(request, 'index.html', page_goods)


@app.route('/search/')
def search(request):  # 搜索
    if request.get('REQUEST_METHOD') == 'GET':
        data = app.args
        page = data.get('page', None)
        c_type = data.get('type', None)
        kwd = data.get('kwd', None)
        if not c_type or not kwd:
            return ('/error/')  # 错误 没搜索内容和类型
        if not page:
            page = 1
        else:
            page = int(page)
    page = page-1
    if c_type == 'name' or c_type == 'tags':
        
        sql = f"SELECT * FROM `goods` where {c_type} LIKE '%{kwd}%' and flags=%s"
        arg=(0,)
    elif c_type == 'price':
        sql = 'SELECT * FROM `goods` where price <%s and flags=%s'
        arg=(kwd,0)
    else:
        return ('/error/')  # 错误 防止异常数据
    page_goods = deal_goods_page(sql,arg, page)
    page_goods.update({'c_type': c_type, 'kwd': kwd})
    return app.render(request, 'search.html', page_goods)


@app.route('/login/')
def login(request):  # 登陆
    message = ''
    if request.get('REQUEST_METHOD') == 'POST':
        data = app.form
        username = data.getvalue("username")
        password = data.getvalue("password")
        sql = 'SELECT * FROM `user` where username=%s'
        arg=(username,)
        # user = session.query(User).filter_by(username=username).first()
        user = select(sql,arg, USER)
        if user:
            user = user[0]
            if user.password == password:
                message = '登陆成功'
                app.set_session(
                    request, {'username': user.username, 'user_id': user.id, 'is_login': True})
                return redirect('/')
            else:
                message = '密码错误'
        else:
            message = '用户不存在'

    return app.render(request, 'login.html', {'message': message})


@app.route('/logout/')
def logout(request):  # 登出
    app.set_session(request, {'is_login': False})

    return redirect('/')  # app.render(request, 'index.html', {})


@app.route('/register/')
def register(request):  # 注册
    message = ''
    if request.get('REQUEST_METHOD') == 'POST':
        data = app.form

        username = data.getvalue("username")
        sql = 'SELECT * FROM `user` where username=%s'
        arg=(username,)
        user = select(sql,arg, USER)
        if not user:

            password = data.getvalue("password")
            password2 = data.getvalue("password2")
            if password == password2:

                truename = data.getvalue("truename")
                birthday = data.getvalue("birthday")
                phone = data.getvalue("phone")
                address = data.getvalue("address")
                zipcode = data.getvalue("zipcode")
                sql = "INSERT INTO `user` (`username`, `password`, `truename`, `birthday`, `phone`, `address`, `zipcode`) VALUES (%s, %s, %s, %s, %s, %s, %s)"
                arg=(username,password,truename,birthday,phone,address,zipcode)
                insert(sql,arg)

                return redirect('/login/')
            else:
                message = '两次密码输入的不一样'
        else:
            message = '用户已存在'
    return app.render(request, 'register.html', {'message': message})


@app.route('/my/')
def my(request):  # 我的资料
    is_login = app.get_session(request)['session'].get('is_login', None)
    user_id = app.get_session(request)['session'].get('user_id', None)

    if is_login:
        sql = 'SELECT * FROM `user` where id=%s'
        arg=(user_id,)
        user = select(sql,arg, USER)[0]
    else:
        return redirect('/login/')  # 未登录 转跳
    return app.render(request, 'my.html', {'user': user})


@app.route('/my_sell/')
def my_sell(request):  # 我出售的商品
    is_login = app.get_session(request)['session'].get('is_login', None)
    user_id = app.get_session(request)['session'].get('user_id', None)

    if is_login:


        if request.get('REQUEST_METHOD') == 'GET':
            data = app.args
            page = data.get('page', None)
            if not page:
                page = 1
            else:
                page = int(page)
        #     pass
        page = page-1
        sql = 'SELECT * FROM `goods` where own_user=%s'
        arg=(user_id,)
        page_goods = deal_goods_page(sql,arg, page)
    else:
        return redirect('/login/')  # 未登录 转跳
    return app.render(request, 'my_sell.html', page_goods)


@app.route('/my_buy/')
def my_buy(request):  # 我购买的商品
    is_login = app.get_session(request)['session'].get('is_login', None)
    user_id = app.get_session(request)['session'].get('user_id', None)


    if is_login:
        if request.get('REQUEST_METHOD') == 'GET':
            data = app.args
            page = data.get('page', None)
            if not page:
                page = 1
            else:
                page = int(page)
        #     pass
        page = page-1
        sql = 'SELECT * FROM `goods` where buy_user=%s'
        arg=(user_id,)
        page_goods = deal_goods_page(sql,arg, page)

    else:
        return redirect('/login/')  # 未登录 转跳

    return app.render(request, 'my_buy.html', page_goods)


@app.route('/my_add/')
def my_add(request):  # 添加新商品
    is_login = app.get_session(request)['session'].get('is_login', None)
    user_id = app.get_session(request)['session'].get('user_id', None)
    ser_token=app.get_session(request)['session'].get('token', None)
    message = ''
    if not is_login:
        return redirect('/login/')  # 未登录 转跳
    if request.get('REQUEST_METHOD') == 'POST':

        data = app.form
        name = data.getvalue('name')
        price = data.getvalue('price')
        tags = data.getvalue('tags')
        token=data.getvalue('csrf')
        if token!=ser_token:
            return redirect('/error/')

        filename = data['photo'].filename
        photo = data['photo'].file.read()

        img = f'/img/{hash(getRandom()+filename)}.{filename.split(".")[1]}'
        save_as(f'{STATICFILES_DIRS}/{img}', photo)
        description = data.getvalue('description')
        sql = "INSERT INTO `goods` (`name`, `tags`, `price`, `own_user`, `description`, `img`) VALUES (%s, %s, %s, %s, %s, %s)"
        arg=(name,tags,price,user_id,description,img)
        insert(sql,arg)
        message = '添加成功'

    return app.render(request, 'my_add.html', {'message': message})


@app.route('/item_detail/')
def item_detail(request):  # 商品详情
    if request.get('REQUEST_METHOD') == 'GET':
        data = app.args
        buy_user = None
        goods_id = data.get('gid', None)
        if goods_id:
            sql = 'SELECT * FROM `goods` where id=%s'
            arg=(goods_id,)
            goods = select(sql,arg, GOODS)
            goods = deal_tags(goods)[0]
            sql = 'SELECT * FROM `user` where id=%s'
            arg=(goods.own_user,)
            own_user = select(sql,arg, USER)[0]
            if goods.buy_user:
                sql = 'SELECT * FROM `user` where id=%s'
                arg=(goods.buy_user,)
                buy_user = select(sql,arg, USER)[0]
        else:
            return redirect('/error/')

    return app.render(request, 'item_detail.html', {'goods': goods, 'buy_user': buy_user, 'own_user': own_user})


@app.route('/buy_goods/')
def buy_goods(request):  # 购买商品
    is_login = app.get_session(request)['session'].get('is_login', None)
    user_id = app.get_session(request)['session'].get('user_id', None)
    message = ''
    if not is_login:
        return redirect('/login/')  # 未登录 转跳
    if request.get('REQUEST_METHOD') == 'GET':
        data = app.args
        goods_id = data.get('gid', None)

        if goods_id:
            sql = 'SELECT * FROM `goods` where id=%s'
            arg=(goods_id,)
            goods = select(sql,arg, GOODS)
            goods = deal_tags(goods)[0]
            sql = 'SELECT * FROM `user` where id=%s'
            arg=(user_id,)
            user = select(sql,arg, USER)[0]
            if float(user.balance) < float(goods.price):
                return redirect('/my/')  # 钱不够要充值

            if goods.own_user != user_id and goods.flags == 0:
                now = time.localtime()
                buy_time = time.strftime("%Y-%m-%d %H:%M:%S", now)
                sql = "UPDATE `goods` SET `buy_user`=%s, `flags`='1',`buy_time`=%s WHERE (`id`=%s)"
                arg=(user_id,buy_time,goods_id)
                update(sql,arg)
                # balance=1
                sql = "UPDATE `user` SET `balance`=%s WHERE (`id`=%s)"
                arg=(float(user.balance)-float(goods.price),user_id)
                update(sql)
                return redirect('/my_buy/')
    else:
        return redirect('/error/')


@app.route('/delete_goods/')
def delete_goods(request):
    is_login = app.get_session(request)['session'].get('is_login', None)
    if not is_login:
        return redirect('/login/')  # 未登录 转跳
    if request.get('REQUEST_METHOD') == 'GET':
        data = app.args
        gid = data.get('gid')
        if gid:
            sql = "DELETE FROM `goods` WHERE (`id`=%s)"
            arg=(gid,)
            delete(sql,arg)
            return redirect('/my_sell/')  # 到我的出售界面
        else:
            return redirect('/error/')  # 错误 没id

def pay_func(amount,user_id):
   
    AccessKey="1asasasasfasfasfaf"
    time_stamp=str(int(time.time()))
    
    token=hash(AccessKey+time_stamp+amount+user_id)
    payload = {'token': token, 'time_stamp': time_stamp,'amount':amount,'user_id':user_id}
    api_url=PAY_API
    url=api_url+'?'+'&'.join(f'{i}={j}' for i,j in payload.items())

    return redirect(url)


@app.route('/recharge1/')
def recharge1(request):
    if request.get('REQUEST_METHOD') == 'GET':
        data = app.form
        user_id=data.getvalue('user_id')
        amount = data.getvalue('amount')  # 数量

        """在这里与支付平台对接"""

        sql = 'SELECT * FROM `user` where id=%s'
        arg=(user_id,)
        user = select(sql,arg, USER)[0]
        sql = "UPDATE `user` SET `balance`=%s WHERE (`id`=%s)"
        arg=(float(user.balance)+float(amount),user_id)
        update(sql,arg)
        return json.dumps({'state':'ok'})


@app.route('/recharge/')
def recharge(request):  # 充值
    is_login = app.get_session(request)['session'].get('is_login', None)
    user_id = app.get_session(request)['session'].get('user_id', None)
    message = ''
    if not is_login:
        return redirect('/login/')  # 未登录 转跳
    if request.get('REQUEST_METHOD') == 'GET':
        data = app.args
        amount = data.get('amount')  # 数量
    # return app.render(request, 'recharge.html', {'amount': amount, 'message': message})
    return pay_func(str(amount),str(user_id))






